import React from 'react';
import { useRequest } from 'umi';
import { Form, Input, Button, Tooltip } from 'antd';
import { SyncOutlined, SafetyCertificateOutlined } from '@ant-design/icons';
import { getLoginCaptcha as loginCaptcha } from '@/services/umi-demo/verify';

const InputCaptcha: React.FC<{}> = () => {
  const { data, error, run, loading } = useRequest(loginCaptcha);

  /** Button点击事件 */
  const onClick = () => {
    run();
  };

  /** 刷新按键 */
  const ReloadButton = () => {
    return (
      <Tooltip title="刷新验证码">
        <Button
          style={{
            height: '39.8px',
            width: '39.8px',
          }}
          disabled={loading}
          onClick={onClick}
          icon={<SyncOutlined spin={loading} />}
        ></Button>
      </Tooltip>
    );
  };

  return (
    <>
      <Form.Item
        name={'verify'}
        rules={[
          // https://ant.design/components/form-cn/#Form.Item
          ({ getFieldValue }) => ({
            validator(_, value) {
              if (error) {
                return Promise.reject(new Error('请重新获取验证码！'));
              }
              if (!value) {
                return Promise.reject(new Error('请输入验证码！'));
              }
              if (data?.toLocaleUpperCase() === value.toLocaleUpperCase()) {
                return Promise.resolve();
              }
              return Promise.reject(new Error('验证码错误！'));
            },
          }),
        ]}
      >
        <Input
          placeholder={'验证码(不区分大小写)'}
          size={'large'}
          allowClear
          maxLength={4}
          prefix={<SafetyCertificateOutlined className={'prefixIcon'} />}
        />
      </Form.Item>
      <Form.Item name={'captcha'}>
        <Input.Group compact>
          <Input
            size="large"
            disabled
            placeholder="----"
            value={
              loading ? '······' : error ? '请重新获取' : data ? data : '----'
            }
            style={{
              width: '288.2px',
              textAlign: 'center',
            }}
          />
          <ReloadButton />
        </Input.Group>
      </Form.Item>
    </>
  );
};

export default InputCaptcha;
